package com.headwire.kw.helpers;

import java.io.File;
import java.io.PrintStream;

public class FileLister implements Runnable {
	private String path;
	private String prefix = "";
	private String postfix = "";
	private String delimiter = "\n";
	private String[] extension = null;
	private boolean includeDirectories = false;
	private PrintStream out = System.out;
	
	/**
	 * By default prefix is "", delimiter is "\n", it will print files of any
	 * extension and will not print out subdirectories names.
	 * 
	 * @param path Path of directory to print out files
	 */
	public FileLister(String path) {
		this.path = path;
	}
	
	public void run() {
		File folder = new File(path);
		if(folder.isDirectory()){
			for(File file : folder.listFiles())
			{
				if(!file.isDirectory() || includeDirectories) {
					if(file.isDirectory() || validExtension(file)) {
						// print it out!
						CodeHolder.derp(file.getName());
						/*
						out.print(prefix);
						out.print(file.getName());
						out.print(postfix);
						out.print(delimiter);*/
					}
				}
			}
		}
	}
	
	private boolean validExtension(File file) {
		if(extension == null) 
			return true;
		String name = file.getName();
		if(name.equals(""))
			return false;
		for(String ext : extension) {
			if(ext.equals("")) {
				// if a file with no extension is valid, only return true if no period
				if(name.indexOf('.') < 0)
					return true;
				else
					continue;
			}
			if(name.endsWith(ext))
				return true;
		}
		return false;
	}
	
	public void setPrefix(String p) {
		this.prefix = p;
	}
	
	public void setDelimiter(String delim) {
		this.delimiter = delim;
	}
	
	public void setPostfix(String p) {
		this.postfix = p;
	}
	
	public void setExtension(String e) {
		this.extension = new String[]{e};
	}
	
	public void setExtensions(String[] e) {
		this.extension = e;
		
	}
	
	public void printSubDirectories(boolean d) {
		this.includeDirectories = d;
	}
}
